<template>
  <div class="daily-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>日常笔记</h1>
      <p>记录生活点滴，分享日常感悟</p>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <el-row :gutter="20" align="middle">
        <el-col :span="8">
          <el-select v-model="queryParams.categoryId" placeholder="选择分类" clearable @change="handleQuery">
            <el-option label="全部分类" value="" />
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-select v-model="queryParams.sortBy" placeholder="排序方式" @change="handleQuery">
            <el-option label="最新发布" value="createTime" />
            <el-option label="最多点赞" value="likeCount" />
            <el-option label="最多收藏" value="favoriteCount" />
            <el-option label="最多评论" value="commentCount" />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-input
            v-model="queryParams.keyword"
            placeholder="搜索笔记内容..."
            @keyup.enter="handleQuery"
          >
            <template #append>
              <el-button @click="handleQuery">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-col>
      </el-row>
    </div>

    <!-- 笔记列表 -->
    <div class="notes-list" v-loading="loading">
      <el-row :gutter="20">
        <el-col :span="24" v-if="noteList.length === 0 && !loading">
          <el-empty description="暂无日常笔记" />
        </el-col>
        <el-col :span="24" v-for="note in noteList" :key="note.noteId">
          <el-card class="note-card" shadow="hover" @click="goToDetail(note.noteId)">
            <div class="note-content">
              <div class="note-header">
                <h3 class="note-title">{{ note.title }}</h3>
                <div class="note-meta">
                  <el-tag v-if="note.categoryName" size="small" type="info">
                    {{ note.categoryName }}
                  </el-tag>
                  <span class="note-date">{{ formatDate(note.createTime) }}</span>
                </div>
              </div>

              <div class="note-body">
                <!-- 使用 v-html 渲染富文本内容 -->
                <div class="note-summary" v-html="getNoteSummary(note.content)"></div>

                <!-- 标签 -->
                <div class="note-tags" v-if="note.tags">
                  <el-tag
                    v-for="tag in note.tags.split(' ')"
                    :key="tag"
                    size="small"
                    effect="plain"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
              </div>

              <div class="note-footer">
                <div class="note-author">
                  <el-avatar :size="24" :src="note.userAvatar">
                    {{ note.createBy?.charAt(0) }}
                  </el-avatar>
                  <span class="author-name">{{ note.createBy }}</span>
                </div>

                <div class="note-stats">
                  <span class="stat-item">
                    <el-icon><View /></el-icon>
                    {{ note.viewCount || 0 }}
                  </span>
                  <!-- 根据你的数据结构调整其他统计字段 -->
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="total > 0">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleQuery"
        @current-change="handleQuery"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, View, Star, Collection, ChatDotRound } from '@element-plus/icons-vue'
import { getPublicDailyNotes, getNoteCategories } from '@/api/note'
import type { NoteDaily, NoteCategory, NoteQuery } from '@/types/api'
import dayjs from 'dayjs'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const noteList = ref<NoteDaily[]>([])
const categories = ref<NoteCategory[]>([])
const total = ref(0)

// 查询参数
const queryParams = reactive<NoteQuery>({
  pageNum: 1,
  pageSize: 20,
  keyword: '',
  categoryId: '',
  sortBy: 'createTime'
})

// 获取笔记摘要（限制长度并保持HTML格式）
const getNoteSummary = (content: string) => {
  if (!content) return ''

  // 限制内容长度，但保持HTML结构
  const maxLength = 200
  if (content.length <= maxLength) {
    return content
  }

  // 简单截取，实际项目中可能需要更复杂的HTML安全截取
  return content.substring(0, maxLength) + '...'
}

// 获取笔记列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getPublicDailyNotes(queryParams)
    console.log('后端返回数据:', response) // 调试用

    if (response.code === 200) {
      // 根据实际数据结构调整
      if (response.data) {
        // 如果数据在data字段中
        noteList.value = response.data.rows
        total.value = response.data.total
      } else {
        // 如果数据直接在根级别
        noteList.value = response.rows
        total.value = response.total
      }
    } else {
      ElMessage.error(response.msg || '获取笔记列表失败')
    }
  } catch (error) {
    console.error('获取笔记列表失败:', error)
    ElMessage.error('获取笔记列表失败')
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const getCategoriesList = async () => {
  try {
    const response = await getNoteCategories()
    if (response.code === 200) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 搜索处理
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 跳转到详情页
const goToDetail = (id: number) => {
  router.push(`/note/daily/${id}`)
}

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

// 页面初始化
onMounted(() => {
  getList()
  getCategoriesList()
})
</script>

<style scoped>
.daily-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 2.5rem;
  color: #303133;
  margin-bottom: 10px;
}

.page-header p {
  font-size: 1.1rem;
  color: #909399;
}

.filter-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.notes-list {
  min-height: 400px;
}

.note-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.note-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.note-content {
  padding: 10px;
}

.note-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.note-title {
  font-size: 1.3rem;
  color: #303133;
  margin: 0;
  flex: 1;
  margin-right: 15px;
}

.note-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-shrink: 0;
}

.note-date {
  color: #909399;
  font-size: 0.9rem;
}

.note-body {
  margin-bottom: 20px;
}

.note-summary {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 15px;
  max-height: 120px;
  overflow: hidden;
}

.note-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.note-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.note-author {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-name {
  color: #606266;
  font-size: 0.9rem;
}

.note-stats {
  display: flex;
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 0.9rem;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 富文本内容样式 */
:deep(.note-summary .ql-code-block-container) {
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 12px;
  margin: 8px 0;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  overflow-x: auto;
}

:deep(.note-summary .ql-code-block) {
  margin: 4px 0;
  line-height: 1.4;
  white-space: pre-wrap;
}

:deep(.note-summary p) {
  margin: 8px 0;
  line-height: 1.6;
}

:deep(.note-summary h1),
:deep(.note-summary h2),
:deep(.note-summary h3) {
  margin: 16px 0 8px 0;
  color: #303133;
  font-weight: 600;
}

:deep(.note-summary ul),
:deep(.note-summary ol) {
  margin: 8px 0;
  padding-left: 24px;
}

:deep(.note-summary li) {
  margin: 4px 0;
  line-height: 1.5;
}

:deep(.note-summary blockquote) {
  border-left: 4px solid #409eff;
  background: #f0f7ff;
  margin: 12px 0;
  padding: 12px 16px;
  font-style: italic;
}

@media (max-width: 768px) {
  .daily-view {
    padding: 10px;
  }

  .page-header h1 {
    font-size: 2rem;
  }

  .filter-section {
    padding: 15px;
  }

  .note-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .note-meta {
    width: 100%;
    justify-content: space-between;
  }

  .note-footer {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .note-stats {
    width: 100%;
    justify-content: space-around;
  }
}
</style>
